//
//  PhotoCollectionViewCell.swift
//  weibo
//
//  Created by 叶子韬韬 on 2017/5/13.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
import SDWebImage
class PhotoCollectionViewCell: UICollectionViewCell {
    var picUrl:URL? {
        didSet{
            
            guard let picUrl = picUrl else {
                return
            }
            
            //取出image
            let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picUrl.absoluteString)
            
            //计算imageView的frame
            let x:CGFloat = 0
            let width = UIScreen.main.bounds.width
            let height = width/image!.size.width * image!.size.height
            var y:CGFloat = 0
            
            if height>UIScreen.main.bounds.height {
                y = 0
            }else{
                y = (UIScreen.main.bounds.height-height)*0.5
            }
            
            self.imageView.frame = CGRect.init(x: x, y: y, width: width, height: height)
            
            
            //获取大图的url
            let smallUrlStr = picUrl.absoluteString
            let bigUrlStr = smallUrlStr.replacingOccurrences(of: "thumbnail", with: "bmiddle")
            self.progessView.isHidden = false
            imageView.sd_setImage(with: URL(string: bigUrlStr), placeholderImage: image, options: [], progress: { (current, total,_) in
                
                
                self.progessView.progess = CGFloat(current)/CGFloat(total)
                
                
            }) { (_, _, _,_) in
                self.progessView.isHidden = true
            }
            
            
            //设置图片
            self.imageView.image = image
            
            //设置scrollview contensize
            self.scrollView.contentSize = CGSize.init(width: 0, height: height)
            
        }
    }
    
    internal lazy var scrollView:UIScrollView = UIScrollView()
    internal lazy var imageView:UIImageView = UIImageView()
    internal lazy var progessView:ProgessView = ProgessView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}
extension PhotoCollectionViewCell {
    internal func setupUI(){
        
        contentView.addSubview(scrollView)
        contentView.addSubview(progessView)
        scrollView.addSubview(imageView)
        
        scrollView.frame = frame
        progessView.bounds = CGRect.init(x: 0, y: 0, width: 50, height: 50)
        progessView.center = CGPoint.init(x: UIScreen.main.bounds.width*0.5, y: UIScreen.main.bounds.height*0.5)
        progessView.isHidden = true
        progessView.backgroundColor = UIColor.clear
        
    }
}

